import { defineStore } from "pinia";
import { getQuestions } from "@/api/question";
import { QUESTION_SORT_BY } from "@/assets/js/const";
import { canUpdateCached } from "@/assets/js/utils";
import useApiCallback from "@/hooks/useApiCallback";

const [fetchQuestionList, loading] = useApiCallback(async ({ page, limit, sortBy }) => {
  return await getQuestions({ page, limit, sortBy })
})

const [getQuestionList, updateQuestionList] = canUpdateCached(async (typeStr) => {
  let [page, limit, sortBy] = typeStr.split('-')
  page = Number(page) ? Number(page) : 1
  limit = Number(limit) ? Number(limit) : undefined
  sortBy = sortBy === 'undefined' ? QUESTION_SORT_BY.READ_NUMBER : sortBy
  const result = await fetchQuestionList({ page, limit, sortBy })
  if (result.code === 0) {
    return [result.data, result.total]
  }
})

const useQuestionStore = defineStore('question', {
  state() {
    return {
      page: 1,
      limit: 10,
      sortBy: QUESTION_SORT_BY.READ_NUMBER,
      total: 0,
      loading,
      questionList: []
    }
  },
  actions: {
    async updateQuestionList() {
      const [questionList, total] = await updateQuestionList(`${this.page}-${this.limit}-${this.sortBy}`)
      this.questionList = questionList
      this.total = total
    },
    async getQuestionList({ page, limit, sortBy } = {}) {
      this.page = page
      this.limit = limit
      this.sortBy = sortBy
      const [questionList, total] = await getQuestionList(`${page}-${limit}-${sortBy}`)
      this.questionList = questionList
      this.total = total
    }
  }
})

export default useQuestionStore
